import { login } from '@/api/login/user'
import { getToken, setToken, removeToken } from '@/utils/auth'

const state = {
  token: getToken()
}

const actions = {
  login ({ commit }, loginInfo) {
    return new Promise((resolve, reject) => {
      login(loginInfo).then(response => {
        // 登录成功，设置token
        commit('SET_TOKEN', response.token)
        setToken(response.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  logout ({ commit }) {
    return new Promise((resolve, reject) => {
      commit('SET_TOKEN', '')
      removeToken()
      resolve()
    })
  },
  resetToken ({ commit }) {
    return new Promise((resolve, reject) => {
      commit('SET_TOKEN', '')
      removeToken()
      resolve()
    })
  }
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
